package com.vmix.android.vmixsdk.rds;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidParameterException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.vmix.android.vmixsdk.config.VmixConfig;
import com.vmix.android.vmixsdk.exception.VmixException;
import com.vmix.android.vmixsdk.exception.VmixParseException;
import com.vmix.android.vmixsdk.valueobject.VmixCollection;
import com.vmix.android.vmixsdk.valueobject.VmixCollections;

/**
 * Get A List of Connections based on the container collection
 * 
 * @author lei
 *
 */
public class GetCollectionsOperation extends AbstractOperation {

	protected String action = "getCollections";
	
	/**
	 * constructor
	 */
	public GetCollectionsOperation() throws VmixException {
	
		if( VmixConfig.COLLECTION.length() < 1 ) {
		
			throw new VmixException("Missing COLLECTION service URL in VmixConfig");
		}
		
		if( VmixConfig.ATOKEN.length() < 1 ) {
			
			throw new VmixException("Missing ATOKEN in VmixConfig");
			
		}
		
		this.serviceUrl = VmixConfig.COLLECTION;
	
	}
	
	/**
	 * process to get a list of collections
	 * 
	 * @return
	 * @throws VmixException
	 */
	public VmixCollections process() throws VmixException {
	
		// build out the request url
		this.serviceUrl += "action=" + this.action + "&collection_ids="+ VmixConfig.CONTAINER_COLLECTION 
			+ "&atoken="+ VmixConfig.ATOKEN+"&output=xml";
		Log.v("getCollecitonOperation", this.serviceUrl);
		
		VmixCollections collections = new VmixCollections();
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		try {

			// build out new url object
			URL url = new URL( this.serviceUrl );
			URLConnection connection = url.openConnection();
			
			HttpURLConnection httpConnection = (HttpURLConnection)connection;
			
			// get respone code
			int responseCode = httpConnection.getResponseCode();
			
			// if the response code is not ok
			if( responseCode != HttpURLConnection.HTTP_OK ) {
				throw new HttpException();
			}
			
			InputStream inputStream = httpConnection.getInputStream();
			
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse( inputStream );
			
			Element root = dom.getDocumentElement();
			NodeList items = root.getElementsByTagName( "collection" );
			
			for( int i = 0; i < items.getLength(); i++ ) {

				VmixCollection collection = new VmixCollection();
				
				// get media item
				Node collectionItem = items.item(i);
				NodeList properties = collectionItem.getChildNodes();

				// get a list of the childnodes
				for( int j = 0; j < properties.getLength(); j++ ) {
					
					// pull out property name and value
					Node property = properties.item(j);
					String propertyName = property.getNodeName();

					// set id
					if( propertyName.equalsIgnoreCase("id") ) {
						collection.setCollectionId(property.getFirstChild().getNodeValue());
					}
					// set partner id
					else if( propertyName.equalsIgnoreCase("token") ) {
						collection.setToken(property.getFirstChild().getNodeValue());
					}
					// set title
					else if( propertyName.equalsIgnoreCase("name")) {
						Log.d("COLLECTION", "NAME: " + property.getFirstChild().getNodeValue());
						collection.setName(property.getFirstChild().getNodeValue());
					}
					// TODO - need to sanitize the next few items
					// set description
					/*else if( propertyName.equalsIgnoreCase("description") ) {
						collection.setDescription((String)property.getFirstChild().getNodeValue() );
					}
					// set class_id
					else if( propertyName.equalsIgnoreCase("status") ) {
						collection.setStatus((String)property.getFirstChild().getNodeValue());
					}
					// set date created
					else if( propertyName.equalsIgnoreCase("date_created") ) {
						collection.setDateCreated((String)property.getFirstChild().getNodeValue());
					}
					// set date approved
					else if( propertyName.equalsIgnoreCase("last_modified") ) {
						collection.setLastModified((String)property.getFirstChild().getNodeValue());
					}
					// set last modified
					else if( propertyName.equalsIgnoreCase("search_query") ) {
						collection.setLastModified((String)property.getFirstChild().getNodeValue());
					}
					// set source name
					else if( propertyName.equalsIgnoreCase("owner_partner_id") ) {
						collection.setOwnerPartnerId((String)property.getFirstChild().getNodeValue());
					}
					// set total views
					else if( propertyName.equalsIgnoreCase("thumbnail_media_id") ) {
						collection.setThumbnailMediaId((String)property.getFirstChild().getNodeValue());
					}
					*/
				}
					
				if( collection.getCollectionId().equals( VmixConfig.CONTAINER_COLLECTION)) {
					continue;
				}
				
				collections.add( collection );
			
			}
			
			return collections;
		}
		catch( InvalidParameterException e ) {
			throw new VmixException("INVALID PARAMETERS: " + e.getMessage());
		}
		catch( IOException e ) {
			throw new VmixException("IOException: " + e.getMessage());
		}
		catch( Exception e ) {
			Log.v( "EXCEPTION", e.getMessage());
			throw new VmixException( e.getMessage() );
		}
	}
}
